package com.example.android.apis;

import java.io.BufferedReader;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.imi.threads.SWThreadExecutor;

public class ApiDemos extends TabActivity implements TabHost.TabContentFactory {
	/** Called when the activity is first created. */
	
	public static Map<String, NewsAdapter> map ;
	public static SWThreadExecutor exec = new SWThreadExecutor();
	Handler handler;
	private int viewnum=0;
	
	/**
	 * @author nehil
	 * The variables required for updating the news on facebook
	 */
	private static final String FACEBOOK_APPID = "239920396037320";
	private static final String FACEBOOK_PERMISSION = "publish_stream";
	private static final String TAG = "FacebookSample";
	private static final String MSG = "Nehil is trying to update";
	private final Handler mFacebookHandler = new Handler();
	private TextView loginStatus;
	private FacebookConnector facebookConnector;
	
	
	final Runnable mUpdateFacebookNotification = new Runnable() {
        public void run() {
        	Toast.makeText(getBaseContext(), "Facebook updated !", Toast.LENGTH_LONG).show();
        }
    };
    
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		map = Collections.synchronizedMap(new HashMap<String,NewsAdapter>());
		handler = new Handler();
		/**
		 * Example of using a tab content factory for the content via
		 * {@link TabHost.TabSpec#setContent(android.widget.TabHost.TabContentFactory)}
		 * 
		 * It also demonstrates using an icon on one of the tabs via
		 * {@link TabHost.TabSpec#setIndicator(CharSequence, android.graphics.drawable.Drawable)}
		 * 
		 */
		setContentView(R.layout.main);
		TabHost.TabSpec spec;
		
		/**
		 * @author nehil
		 * instatiating the facebookConnector object.
		 */
		this.facebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});
		
		
		final TabHost tabHost = getTabHost();
	
		tabHost.addTab(tabHost
				.newTabSpec("latestnews")
				.setIndicator("Latest News",
						getResources().getDrawable(R.drawable.icon))
				.setContent(this));
		tabHost.addTab(tabHost.newTabSpec("transfernews")
				.setIndicator("Transfer News").setContent(this));
		tabHost.setCurrentTab(0);
		
	}

	/** {@inheritDoc} */
	public View createTabContent(String tag) {
		tag = tag.toLowerCase();
		//ListView view = (ListView) findViewById(R.id.ListView01);
		final ListView view = new ListView(this);
		NewsAdapter newsAdapter = null;
		ArrayList<News> list = null;
		
		/**
		 * @author nehil
		 * This is where the quick action bar is setup.
		 */
		
		
		final ActionItem facebookAction = new ActionItem();
		facebookAction.setTitle("Share");
		facebookAction.setIcon(getResources().getDrawable(R.drawable.facebook));
		
		final ActionItem twitterAction = new ActionItem();
		twitterAction.setTitle("Tweet");
		twitterAction.setIcon(getResources().getDrawable(R.drawable.twitter));
		
		final ActionItem commentAction = new ActionItem();
		commentAction.setTitle("Comment");
		commentAction.setIcon(getResources().getDrawable(R.drawable.comment));
		
			
		view.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
			{
				viewnum = arg2;
				Intent intent = new Intent().setClass(getApplicationContext(), NewsActivity.class);
				News activityNews = ((NewsView) arg1).getNews();
				String activitytexturl = activityNews.actualtexturl;
				
				intent.putExtra("newsurl",activitytexturl);
        		startActivityForResult(intent, 0);				
			}
		});
		
		/**
		 * @author nehil
		 */
		
		
		view.setOnItemLongClickListener(new OnItemLongClickListener(){
			public boolean onItemLongClick(AdapterView<?> arg0, View view,
			int position, long id) {
			// TODO Auto-generated method stub
				Log.d("longclick","here 135");
				final QuickAction mQuickAction 	= new QuickAction(view);			
				
				final ImageView mMoreImage 		= (ImageView) view.findViewById(R.id.i_more);
				
				
				
				//mMoreImage.setImageResource(R.drawable.ic_list_more_selected);
				
				facebookAction.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						Toast.makeText(ApiDemos.this, "Facebook " , Toast.LENGTH_SHORT).show();
				    	
						mQuickAction.dismiss();
			        	
			           
					}
				});
				twitterAction.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						Toast.makeText(ApiDemos.this, "Twitter " , Toast.LENGTH_SHORT).show();
				    	
						mQuickAction.dismiss();
					}
				});
				
				commentAction.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						Toast.makeText(ApiDemos.this, "Comment " , Toast.LENGTH_SHORT).show();
				    	
						mQuickAction.dismiss();
					}
				});
				
				mQuickAction.addActionItem(facebookAction);
				mQuickAction.addActionItem(twitterAction);
				mQuickAction.addActionItem(commentAction);
				
				mQuickAction.setAnimStyle(QuickAction.ANIM_AUTO);
				
				mQuickAction.setOnDismissListener(new OnDismissListener() {
					
					public void onDismiss() {
						//mMoreImage.setImageResource(R.drawable.ic_list_more);
					}
				});
				
				mQuickAction.show();
				
				
				
				
			return false;
			}

			});
		/**
		 * @author Jatin
		 */
		
		if(map.get(tag)==null)
		{
			list = new ArrayList<News>();
			newsAdapter = new NewsAdapter(this,list);
			setList(list);
			updateList(list,newsAdapter,tag);
			view.setAdapter(newsAdapter);
			map.put(tag, newsAdapter);
		}
		else 
		{
			Log.d("JSON","here 108"); 
			newsAdapter  = map.get(tag);
			list = (ArrayList<News>) newsAdapter.list;
			setList(list);
			view.setAdapter(newsAdapter);
			updateList(list,newsAdapter,tag);
			map.put(tag, newsAdapter);
		}
		
		return view;
		
	}
	
	
	private ArrayList<News> dupList = null;
	private News getFromList(int position)
	{
		return dupList.get(position);
	}
	private void setList(ArrayList<News> l)
	{
		dupList = l;
	}
	
	
	private void updateList(final ArrayList<News> list,final NewsAdapter newsadap,final String tag)
	{
		final ArrayList<String> urllist = new ArrayList<String>();
		ArrayList<ImageView> image = new ArrayList<ImageView>();
		
		ApiDemos.exec.execute(new Runnable()
		{
			public void run(){
				
				String s = new String("");
				try {
				URL url = new URL("http://e-caffeine.net/news.txt");
				 s =getJSONScoreStringFromNet(url);
				 JSONArray main = new JSONArray(s);	
				JSONObject latest = null;
				Log.d("JSON","here 135");
				if(tag.equals("latestnews"))
				{latest = (JSONObject) main.get(0);}
				else if(tag.equals("transfernews"))
				latest = (JSONObject) main.get(1);
				else latest = null;
				Log.d("JSON","here 146");
					JSONArray lnews = latest.getJSONArray("news");
					for(int i =0;i<lnews.length();i++)
					{
						JSONObject ob = lnews.getJSONObject(i);
						News n = new News();
						n.picurl = ob.getString("picurl");Log.d("JSON",n.picurl);
						urllist.add(n.picurl);
						n.newstext = ob.getString("text"); 
						n.whichnews = tag;Log.d("JSON",tag);
						
						URL ur = new URL(n.picurl);
						InputStream ins = null;
					    try {
					        ins = ur.openStream();
					    } catch (MalformedURLException e) {
					        e.printStackTrace();
					    } catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
					    final Bitmap b = BitmapFactory.decodeStream(new FlushedInputStream(ins));
					    n.bit = b;					    
						list.add(n);
						handler.post(new Runnable(){
							public void run(){
								
								
								newsadap.notifyDataSetChanged();

							}});
					}

	 					handler.post(new Runnable(){
						public void run(){
							
							newsadap.notifyDataSetChanged();
							

						}
						
					
					});
					
	 					
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();}
//				 catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				

			}
		});
		
	}
	
	private String getJSONScoreStringFromNet(URL urladdress) {

		InputStream instream = null;
		BufferedReader read = null;
		try {
			instream = urladdress.openStream();
			read = new BufferedReader(new InputStreamReader(instream));
			String s = new String("");
			String line = null;
			while ((line = read.readLine()) != null) {
				s = s + line;
			}
			return s;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				read.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		this.facebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
	}
	
	
	
	protected void onResume() {
		super.onResume();
		//updateLoginStatus();
	}
	

	private String getFacebookMsg() {
		return MSG + " at " + new Date().toLocaleString();
	}	
	
	public void postMessage() {
		
		if (facebookConnector.getFacebook().isSessionValid()) {
			postMessageInThread();
		} else {
			SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {
				
				public void onAuthSucceed() {
					postMessageInThread();
				}
				
				
				public void onAuthFail(String error) {
					
				}
			};
			SessionEvents.addAuthListener(listener);
			facebookConnector.login();
		}
	}

	private void postMessageInThread() {
		Thread t = new Thread() {
			public void run() {
		    	
		    	try {
		    		facebookConnector.postMessageOnWall(getFacebookMsg());
					mFacebookHandler.post(mUpdateFacebookNotification);
				} catch (Exception ex) {
					Log.e(TAG, "Error sending msg",ex);
				}
		    }
		};
		t.start();
	}

	private void clearCredentials() {
		try {
			facebookConnector.getFacebook().logout(getApplicationContext());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	private class FlushedInputStream extends FilterInputStream {
	    public FlushedInputStream(InputStream inputStream) {
	        super(inputStream);
	    }

	    
	    public long skip(long n) throws IOException {
	        long totalBytesSkipped = 0L;
	        while (totalBytesSkipped < n) {
	            long bytesSkipped = in.skip(n - totalBytesSkipped);
	            if (bytesSkipped == 0L) {
	                int b = read();
	                if (b < 0) {
	                    break; // we reached EOF
	                } else {
	                    bytesSkipped = 1; // we read one byte
	                }
	            }
	            totalBytesSkipped += bytesSkipped;
	        }
	        return totalBytesSkipped;
	    }
	}

}

